//
//  SearchViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/16.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "SearchViewController.h"
#import "YBPopupMenu.h"
#import "UIView+Extend.h"
#import "LooseModel.h"
#import "ProductModel.h"
#import "MarketSearchResultVC.h"
#import "ShopDetailViewController.h"
#import "StoreViewController.h"

#define TITLES @[@"商品", @"店铺", @"商场"]
@interface SearchViewController ()<YBPopupMenuDelegate>
@property (strong, nonatomic) IBOutlet UIButton *selecteButn;//搜索框里的选择按钮
@property(nonatomic,strong)YBPopupMenu *popupMenu;//下啦菜单
@property(nonatomic,strong)UIButton *currentSlectedBtn;//记录当前选择的按钮
@property(nonatomic,strong)UIButton *clearBtn;//删除按钮
@property(nonatomic,strong)UILabel *historyLabel;//历史搜索
@property(nonatomic,strong)UIButton *recordBtn;//记录刚刚添加的btn
@property(nonatomic,strong)UILabel *hotSearchLabel;//历史搜索
@property(nonatomic,strong)NSMutableArray *historyArray;//存放历史搜索的内容
@property(nonatomic,strong)NSMutableArray *historyType;//存放历史搜索的类型
@property(nonatomic,strong)NSMutableArray *hotArray;//存放热门搜索的内容
@property(nonatomic,strong)NSMutableArray *hotType;//存放热门搜索的内容
@property(nonatomic,strong)NSMutableArray *allBtn;//记录页面所有的流水布局按钮
@property(nonatomic,strong)NSMutableArray *allBtnType;
@property(nonatomic,strong)UITextField *searchTextField;//搜索输入框
@property(nonatomic,assign)int  popSelectedindex;
@property(nonatomic,strong)NSMutableArray *typeArray;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.typeArray = [NSMutableArray array];
    for(int i=0;i<TITLES.count;i++){
        ProductModel *pmodel = [[ProductModel alloc]init];
        pmodel.name = TITLES[i];
        [self.typeArray addObject:pmodel];
    }
    self.popSelectedindex = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    self.allBtn = [NSMutableArray array];
    self.allBtnType = [NSMutableArray array];
    //从本地获取历史搜索记录
    self.historyArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"historyBtn"] mutableCopy];
    self.historyType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"historyType"] mutableCopy];
    //如果没有记录初始化历史记录数组
    if(self.historyArray ==nil) {
        self.historyArray = [NSMutableArray array];
        self.historyType = [NSMutableArray array];
    }
    
    self.hotArray = [NSMutableArray array];
    self.hotType = [NSMutableArray array];
    //搜索框
    [self  customSearchField];
    //搜索按钮
    [self  searchButton];
  
    //添加点击手势，点击的时候收回键盘和下拉框
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    [self loadHotSearch];
}
//2.70获取热搜词汇
-(void)loadHotSearch{
    __weak typeof(self) weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GETHOTSEARCH paramters:nil afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取热搜词汇----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *data = resultDic[@"data"];
            if([data isKindOfClass:[NSNull class]]){
                return ;
            }
            for(NSDictionary *dic in data){
                [weakSelf.hotArray addObject:dic[@"name"]];
                [weakSelf.hotType addObject:dic[@"type"]];
            }
            //历史搜索和热门搜索
            [weakSelf initSubViews];
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
            //历史搜索和热门搜索
            [weakSelf initSubViews];
        }
    }];
}
-(void)tapAction{
    [self.view endEditing: YES];
    if(_popupMenu){
        [_popupMenu dismiss];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.searchTextField becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //页面将要消失的时候如果下拉菜单正在显示的话，将其移除
    if(_popupMenu){
        [_popupMenu dismiss];
    }
    [self.view endEditing: YES];
}

-(void)initSubViews{
    //如果本地存在历史搜索记录，则显示相关内容，反之，不显示
    if(_historyArray.count){
        [self.view addSubview:self.historyLabel];
        [self.view addSubview:self.clearBtn];
        //历史搜索有数据
        [self initWaterButtonWithTiltleArray:_historyArray index:0];
    }
    if(self.hotArray.count){
        [self.view addSubview:self.hotSearchLabel];
        [self initWaterButtonWithTiltleArray:_hotArray  index:1];
    }
}
//按钮的点击事件
- (void)btnClick:(UIButton*)btn{
        btn.backgroundColor = DEF_COLOR;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if(self.currentSlectedBtn!=nil&&self.currentSlectedBtn!=btn){
                self.currentSlectedBtn.backgroundColor = DEF_COLOR242;
                [self.currentSlectedBtn setTitleColor:DEF_COLOR153 forState:UIControlStateNormal];
        }
    self.currentSlectedBtn = btn;
    NSUInteger  index =  [self.allBtn indexOfObject:btn];
   NSString *type = self.allBtnType[index];
    
    DLog(@"type---%@---looseName-%@",type,btn.currentTitle);
    if([type intValue]==0){
        StoreViewController *storeVc = [[StoreViewController alloc]init];
        storeVc.hidesBottomBarWhenPushed = YES;
        storeVc.isComfromSearchVC = YES;
        storeVc.looseName = btn.currentTitle;
        [self.navigationController pushViewController:storeVc animated:YES];
    }else if([type intValue]==1){
        ShopDetailViewController *shopDetail = [[ShopDetailViewController alloc]init];
        shopDetail.hidesBottomBarWhenPushed = YES;
        shopDetail.isComfromSearchVC = YES;
        shopDetail.shopName = btn.currentTitle;
         [self.navigationController pushViewController:shopDetail animated:YES];
    }else{
        MarketSearchResultVC *marketSearchList = [[MarketSearchResultVC alloc]init];
        marketSearchList.hidesBottomBarWhenPushed = YES;
        marketSearchList.marketName = btn.currentTitle;
        [self.navigationController pushViewController:marketSearchList animated:YES];
    }
    
    
    //保存到历史记录中
    if(![self.historyArray containsObject:btn.currentTitle]){
        //将最新的搜索内容添加到最前面
        [self.historyArray insertObject:btn.currentTitle atIndex:0];
        [self.historyType insertObject:type atIndex:0];
    }else{
        NSInteger index =  [self.historyArray indexOfObject:btn.currentTitle];
        [self.historyArray removeObjectAtIndex:index];
        [self.historyType removeObjectAtIndex:index];
        [self.historyArray insertObject:btn.currentTitle atIndex:0];
        [self.historyType insertObject:type atIndex:0];
    }
    if(self.historyArray.count>15){
        //历史记录书超过15个的时候移除最后一个
        [self.historyArray removeLastObject];
        [self.historyType removeLastObject];
    }
    [[NSUserDefaults standardUserDefaults] setObject:[self.historyArray copy ]forKey:@"historyBtn"];
    [[NSUserDefaults standardUserDefaults] setObject:[self.historyType copy ]forKey:@"historyType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //刷新页面
    [self updateView];
}

//清除按钮
- (void)clear{
    //移除当前数组中的内容
    [self.historyArray removeAllObjects];
    [self.historyType removeAllObjects];
    //移除本地保存的内容
    [[NSUserDefaults standardUserDefaults ]removeObjectForKey:@"historyBtn"];
    [[NSUserDefaults standardUserDefaults ]removeObjectForKey:@"historyType"];
    //移除所有子控件（自定义导航View除外）
    [self.historyLabel removeFromSuperview];
    [self.clearBtn removeFromSuperview];
    [self.hotSearchLabel removeFromSuperview];
    self.hotSearchLabel = nil;
    for(UIButton *btn in self.allBtn){
        [btn removeFromSuperview];
    }
    [self.allBtn removeAllObjects];
    [self.allBtnType removeAllObjects];
    //将_recordBtn设置为nil 是因为热门搜索label的y值设置与之相关
    _recordBtn = nil;
    //添加热门搜索
    [self.view addSubview:self.hotSearchLabel];
    [self initWaterButtonWithTiltleArray:_hotArray index:1];
}
// 右侧搜索按钮
-(void)searchButton{
    UIButton *locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    locationButton.frame=CGRectMake(0, 0, 40, 40);
        [locationButton setImage:[UIImage imageNamed:@"nav_button_sousuo"] forState:UIControlStateNormal];
    [locationButton addTarget:self action:@selector(search_Action) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem = locationButton;
}

//点击搜索按钮事件
- (void)search_Action{
    if(!self.searchTextField.text.length){
        [MBProgressHUD showTipMessageInWindow:@"请输入您想要搜索的内容"];
        return;
    }
    //发出请求获取搜索结果    
    [self searchWithLooseName:self.searchTextField.text];
    //本地保存历史搜索 并刷新页面
    if(![self.historyArray containsObject:self.searchTextField.text]){
        //将最新的搜索内容添加到最前面
        [self.historyArray insertObject:self.searchTextField.text atIndex:0];
        [self.historyType insertObject:[NSString stringWithFormat:@"%d",self.popSelectedindex] atIndex:0];
    }else{
        NSInteger index =  [self.historyArray indexOfObject:self.searchTextField.text];
        int    row =  [self.historyType[index] intValue];
        if(row!=self.popSelectedindex){
            [self.historyArray removeObjectAtIndex:index];
            [self.historyType removeObjectAtIndex:index];
            [self.historyArray insertObject:self.searchTextField.text atIndex:0];
            [self.historyType insertObject:[NSString stringWithFormat:@"%d",self.popSelectedindex] atIndex:0];
        }
    }
    if(self.historyArray.count>15){
        //历史记录书超过15个的时候移除最后一个
        [self.historyArray removeLastObject];
        [self.historyType removeLastObject];
    }
    [[NSUserDefaults standardUserDefaults] setObject:[self.historyArray copy ]forKey:@"historyBtn"];
    [[NSUserDefaults standardUserDefaults] setObject:[self.historyType copy ]forKey:@"historyType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //刷新页面
    [self updateView];
}

-(void)searchWithLooseName:(NSString *)looseName{
    //2.9首页根据产品名字进行产品模糊查询接口（进入商品展示列表页面）
    //2.10店铺查询接口（店铺列表)
    //2.11商场查询接口（商场列表）
    if(self.popSelectedindex==0){//产品查询
        StoreViewController *storeVc = [[StoreViewController alloc]init];
        storeVc.hidesBottomBarWhenPushed = YES;
        storeVc.isComfromSearchVC = YES;
        storeVc.looseName = looseName;
        [self.navigationController pushViewController:storeVc animated:YES];
    }else if(self.popSelectedindex==1){//店铺查询
        ShopDetailViewController *shopDetail = [[ShopDetailViewController alloc]init];
        shopDetail.hidesBottomBarWhenPushed = YES;
        shopDetail.isComfromSearchVC = YES;
        shopDetail.shopName = looseName;
        [self.navigationController pushViewController:shopDetail animated:YES];
    }else if(self.popSelectedindex==2){//商场查询
        MarketSearchResultVC *marketSearchList = [[MarketSearchResultVC alloc]init];
        marketSearchList.hidesBottomBarWhenPushed = YES;
        marketSearchList.marketName = looseName;
        [self.navigationController pushViewController:marketSearchList animated:YES];
    }
}
    
-(void)updateView{
    if(_historyLabel){
        [_historyLabel removeFromSuperview];
        [_clearBtn removeFromSuperview];
    }
    for(UIButton *btn in self.allBtn){
        [btn removeFromSuperview];
    }
    [self.allBtn removeAllObjects];
    [self.allBtnType removeAllObjects];
    [self.hotSearchLabel removeFromSuperview];
    self.hotSearchLabel = nil;
    [self initSubViews];
}

//搜索输入框
- (void)customSearchField{
    //搜索框的父视图
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width-80-40+10, 26)];
    UITextField *searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, backView.width, 26)];
    searchTextField.textColor = [UIColor whiteColor];
    searchTextField.backgroundColor = [UIColor clearColor];
    searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    searchTextField.leftView= _selecteButn;
    searchTextField.leftViewMode =UITextFieldViewModeAlways;
    searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.searchTextField = searchTextField;
    
      //搜索框的外框
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:backView.bounds];
    imageV.image = [UIImage imageNamed:@"shouye_sousuokuang"];
    [backView addSubview:imageV];
    [backView addSubview:searchTextField];
    backView.left = 40;
    backView.centerY = self.naviBar.centerY+9;
    [self.naviBar addSubview:backView];
}

//下拉框
- (IBAction)showOption:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.isSelected){
         _popupMenu = [YBPopupMenu  showAtPoint:CGPointMake(40,self.naviBar.bottom) titles:self.typeArray icons:nil menuWidth:100 view:[UIApplication sharedApplication].keyWindow  delegate:self];
        _popupMenu.text_Color = DEF_COLOR;
        _popupMenu.backGroudColor = [UIColor blackColor];
        _popupMenu.isShowSeparator = YES;
         _popupMenu.seperaterColor = [UIColor colorWithRed:57./255 green:57./255 blue:57./255 alpha:1.];
    }else{
        [_popupMenu dismiss];
    }
}

//下拉框代理
#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
     ProductModel *model = _typeArray[index];
    [self.selecteButn setTitle:model.name forState:UIControlStateNormal];
    [self showOption:self.selecteButn];
    [_popupMenu dismiss];
    DLog(@"点击了 %@ 选项",model.name);
    self.popSelectedindex = (int)index;
}

//拉伸按钮的背景图片
-(UIImage *)resizableImage:(NSString *)imageName {
    UIImage *image = [UIImage imageNamed:imageName];
    CGFloat h = image.size.width * 0.5;
    CGFloat w = image.size.height * 0.5;
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(w, h, w, h) resizingMode:UIImageResizingModeStretch];
}

//流水布局按钮
- (void)initWaterButtonWithTiltleArray:(NSMutableArray*)titleArr index:(int)index{
//    UIImage *newImage = [self resizableImage:@"xinxikuang"];
//    UIImage *newImage = [UIImage imageNamed:@"xinxikuang"];
    CGFloat spaceWith = 10;
    for (int i = 0; i < titleArr.count; i ++)
    {
        NSString *name = titleArr[i];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont systemFontOfSize:11];
        [btn setTitleColor:DEF_COLOR153 forState:UIControlStateNormal];
        CGRect rect = [name boundingRectWithSize:CGSizeMake(1000 , 15) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:btn.titleLabel.font} context:nil];
        CGFloat BtnW = rect.size.width + 20;
        CGFloat BtnH = 20;
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = BtnH/2;
        if (i == 0)
        {
            if(index==0){
                btn.frame =CGRectMake(15, self.historyLabel.bottom+10, BtnW, BtnH);
            }
            if(index==1){
                btn.frame =CGRectMake(15, self.hotSearchLabel.bottom+10, BtnW, BtnH);
            }
        }
        else{
            CGFloat yuWidth = Main_Screen_Width  -self.recordBtn.frame.origin.x-self.recordBtn.frame.size.width;
            if (yuWidth >= BtnW+15+spaceWith) {
                btn.frame =CGRectMake(self.recordBtn.frame.origin.x+self.recordBtn.frame.size.width+ spaceWith, self.recordBtn.top, BtnW, BtnH);
            }else{
                btn.frame =CGRectMake(15, self.recordBtn.bottom+10, BtnW, BtnH);
            }
        }
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitle:name forState:UIControlStateNormal];
        [self.view addSubview:btn];
        self.recordBtn = btn;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [btn setBackgroundImage:newImage forState:UIControlStateNormal];
        [btn setBackgroundColor:DEF_COLOR242];
        [self.allBtn addObject:btn];
        if(index==0){
            [self.allBtnType addObject:self.historyType[i]];
        }else{
            [self.allBtnType addObject:self.hotType[i]];
        }
    }
}

#pragma mark - 懒加载
-(UILabel *)historyLabel{
    if(!_historyLabel){
        _historyLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 15+kNaviBarHeight, 100, 21)];
        _historyLabel.textColor = DEF_COLOR102;
        _historyLabel.text = @"历史搜索";
        _historyLabel.font = [UIFont systemFontOfSize:14];
    }
    return _historyLabel;
}
-(UIButton *)clearBtn{
    if(!_clearBtn){
        _clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _clearBtn.frame = CGRectMake(Main_Screen_Width-14-20, 9+kNaviBarHeight, 28, 30) ;
        [_clearBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 7, 7, 7)];
//        _clearBtn.backgroundColor = [UIColor redColor];
        [_clearBtn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [_clearBtn addTarget:self action:@selector(clear) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearBtn;
}
- (UILabel *)hotSearchLabel{
    if(!_hotSearchLabel){
        if(_recordBtn==nil){
            _hotSearchLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, kNaviBarHeight+15, 100, 21)];
        }else{
            _hotSearchLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, self.recordBtn.bottom+15, 100, 21)];
        }
        _hotSearchLabel.textColor = DEF_COLOR102;
        _hotSearchLabel.text = @"热门搜索";
        _hotSearchLabel.font = [UIFont systemFontOfSize:14];
    }
    return _hotSearchLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
